import React, { useState } from "react";
import contract from "../contracts/Crowdfunding";
import Web3 from "web3";

function CreateProject() {
  const [title, setTitle] = useState("");
  const [desc, setDesc] = useState("");
  const [goal, setGoal] = useState("");
  const [days, setDays] = useState("");

  const handleSubmit = async (e) => {
    e.preventDefault();

    if (!title.trim()) {
      alert("请输入项目标题");
      return;
    }

    if (!desc.trim()) {
      alert("请输入项目描述");
      return;
    }

    if (!goal || isNaN(goal) || Number(goal) <= 0) {
      alert("请输入有效的目标金额（大于 0 的数字）");
      return;
    }

    if (!days || isNaN(days) || parseInt(days) <= 0) {
      alert("请输入有效的持续天数（大于 0 的整数）");
      return;
    }

    try {
      const accounts = await window.ethereum.request({ method: 'eth_accounts' });
      if (!accounts || accounts.length === 0) {
        alert("请先连接 MetaMask 钱包");
        return;
      }

      // 创建新的 Web3 实例
      const web3 = new Web3(window.ethereum);
      
      // 调试信息
      console.log("Goal value:", goal);
      console.log("Goal type:", typeof goal);
      console.log("Goal as string:", goal.toString());
      
      const goalInWei = web3.utils.toWei(goal.toString(), "ether");
      console.log("Goal in Wei:", goalInWei);

      if (!goalInWei) {
        alert("目标金额转换失败，请检查输入");
        return;
      }

      await contract.methods
        .createProject(
          title.trim(),
          desc.trim(),
          goalInWei,
          parseInt(days)
        )
        .send({ from: accounts[0] });
      alert("项目已创建");
    } catch (err) {
      console.error("创建失败:", err);
      alert("❌ 创建失败：" + err.message);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input placeholder="标题" value={title} onChange={(e) => setTitle(e.target.value)} />
      <input placeholder="描述" value={desc} onChange={(e) => setDesc(e.target.value)} />
      <input placeholder="目标金额（ETH）" value={goal} onChange={(e) => setGoal(e.target.value)} />
      <input placeholder="持续天数" value={days} onChange={(e) => setDays(e.target.value)} />
      <button type="submit">创建</button>
    </form>
  );
}

export default CreateProject;